//
//  myViewController.m
//  TinyFortune
//
//  Created by lc on 16/5/26.
//  Copyright © 2016年 lc. All rights reserved.
//

#import "myViewController.h"
#import "informationViewController.h"
#import "PersonelController.h"
#import "loginViewController.h"
#import "loversViewController.h"
#import "comModel.h"
//第三方分享
#import "UMSocial.h"
//图片缓存相关
#import "SDImageCache.h"
@interface myViewController (){
    NSDictionary *_dict;
    AVUser *_user ;
    
}
@property (weak, nonatomic) IBOutlet UILabel *lastLabel;

@end

@implementation myViewController

#pragma mark- 生命周期
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
       //放在异步线程里面刷新数据
    dispatch_async(dispatch_get_main_queue(), ^{
    [self reloadUserData];    
    });
    [self.navigationController.navigationBar setHidden:NO];
    _user = [AVUser currentUser];
    if(_user){
        _lastLabel.text = @"退出登录";
    }else{
        _lastLabel.text = @"登录";
    }

}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self.navigationController.navigationBar setHidden:NO];
    
    
   
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}
#pragma mark - 刷新当前用户的信息
- (void)reloadUserData{
    AVUser *user = [AVUser currentUser];
    if (user) {

        self.nameLabel.text = user.username;
        self.idLabel.text = [NSString stringWithFormat:@"恩爱号:%@",user.mobilePhoneNumber];
        //获取用户头像文件
        AVFile *file = [user objectForKey:@"iconImage"];
        //利用YYModel将头像转换成json
        if (file) {
            //如果文件为空的话,用YYModel转化之后就会崩溃
             _dict = [NSJSONSerialization JSONObjectWithData:file.yy_modelToJSONData options:NSJSONReadingAllowFragments error:nil];
        }
        //利用SD_image将头像放到头像View上
        [self.iconImageView sd_setImageWithURL:[NSURL URLWithString:_dict[@"url"] ]placeholderImage:[UIImage imageNamed:@"default_avatar"]];
    }else{
        self.nameLabel.text = @"还未登陆哟";
        self.idLabel.text = @"";
        self.iconImageView.image = [UIImage imageNamed:@"default_avatar"];
    }
}
#pragma mark - Table view data source
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    //退出登录页面
    if (indexPath.row == 0 &&indexPath.section == 3) {
        loginViewController *loginVC = [loginViewController new];
        UINavigationController *nav = [[UINavigationController alloc]initWithRootViewController:loginVC];
        [self presentViewController:nav animated:YES completion:nil];
        [AVUser logOut];
    }

    
    
        AVUser *user = [AVUser currentUser];
        //个人信息页面
        if (indexPath.row == 0 && indexPath.section == 0) {
            if (user) {
            UIStoryboard *sb = [UIStoryboard storyboardWithName:@"Main" bundle:nil ];
            informationViewController *inf = [sb instantiateViewControllerWithIdentifier:@"informationViewController"];
            
            [self.navigationController pushViewController:inf animated:YES];
            }else{
                UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"亲，抱歉" message:@"先注册一下吧，科科~~" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:nil];
                [alert show];
            }

        }
        //我的恩爱页面
        if (indexPath.row == 0 && indexPath.section == 1) {
            if (user) {
            PersonelController *perVC = [PersonelController new];
            [self.navigationController pushViewController:perVC animated:NO];
            }
            else{
                UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"亲，抱歉" message:@"先注册一下吧，科科~~" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:nil];
                [alert show];
            }
}

        //我的另一半页面
        if (indexPath.row == 1 && indexPath.section == 1) {
            if (user) {
            if ([user objectForKey:@"lovers"]) {
                PersonelController *perVC = [PersonelController new];
                perVC.loversId = [user objectForKey:@"lovers"];
                [self.navigationController pushViewController:perVC animated:NO];
            }else{
            loversViewController *lovers = [loversViewController new];
            [self.navigationController pushViewController:lovers animated:YES];
            }
            }else{
                UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"亲，抱歉" message:@"先注册一下吧，科科~~" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:nil];
                [alert show];
            }

        }
    //解除关系
    if (indexPath.row == 2 && indexPath.section == 1) {
        if (user) {
           
            if ([[user objectForKey:@"lovers"] length] >1) {
                 NSString *str = [user objectForKey:@"lovers"];
                UIAlertController *alertAC = [UIAlertController alertControllerWithTitle:@"解除关系" message:@"您确定要解除关系吗?" preferredStyle:UIAlertControllerStyleAlert];
                UIAlertAction *yesAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
                    [[DatabaseManager defaultManager] deleteAllObject:[comModel class]];
                    [[DatabaseManager defaultManager] deleteAllObject:[AVIMTextMessage class]];
                    [[DatabaseManager defaultManager] deleteAllObject:[AVIMAudioMessage class]];
                    [user setObject:nil forKey:@"lovers"];
                    [user saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
                        if (succeeded) {
                            AVObject *objcc = [[AVObject alloc]initWithClassName:@"cancelLover"];
                            [objcc setObject:user.mobilePhoneNumber forKey:@"myId"];
                            [objcc setObject:str forKey:@"Id"];
                            [objcc saveInBackground];
                        }else{
                            NSLog(@"%@",error.localizedDescription);
                        }
                    }];
                }];
                UIAlertAction *noAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
                    [alertAC dismissViewControllerAnimated:YES completion:nil];
                }];
                [alertAC addAction:yesAction];
                [alertAC addAction:noAction];
                [self presentViewController:alertAC animated:NO completion:nil];
            }else{
                UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"亲，抱歉" message:@"您还没有添加情侣呢" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:nil];
                [alert show];
            }
        }else{
            UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"亲，抱歉" message:@"先注册一下吧，科科~~" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:nil];
            [alert show];
        }
        
    }

        //清除缓存
        if (indexPath.row == 2 && indexPath.section == 2) {
            //获取缓存信息
            NSInteger imageCount = [[SDImageCache sharedImageCache]getDiskCount];
            //获取图片缓存的大小(单位是字节数)
            CGFloat imageSize = [[SDImageCache sharedImageCache] getSize];
            NSString *msg = [NSString stringWithFormat:@"缓存文件个数:%ld%.1f M",imageCount,(imageSize/1024.0)/1024.0];
            //清除缓存
            UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"清除缓存" message:msg preferredStyle:UIAlertControllerStyleAlert];
            //添加AlertAction
            UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
                [alert dismissViewControllerAnimated:YES completion:nil];
            }];
            //清除按钮
            UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"清除" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
                //清除缓存
                [[SDImageCache sharedImageCache]clearDisk];
                [[SDImageCache sharedImageCache]clearMemory];
                //清除已过期的图片
                [[SDImageCache sharedImageCache]cleanDisk];
            }];
            //讲Action添加到AlertController中
            [alert addAction:cancelAction];
            [alert addAction:okAction];
            //present
            [self presentViewController:alert animated:YES completion:nil];
           
        }
                //第三方分享
        if (indexPath.row ==3 && indexPath.section == 2) {
            //第一个参数:按钮显示的位置
            //第二个参数:appkey
            //第三个参数:你要分享的文字
            [UMSocialSnsService presentSnsIconSheetView:self
                                                 appKey:UMSocialAppKey
                                              shareText:@"快点加入小幸运吧！！"
                                             shareImage:nil
                                        shareToSnsNames:nil
                                               delegate:nil];
        }

    
    
}

@end
